import React, {useEffect, useState} from 'react';
import {Form, Button, DatePicker, Input, Modal, Row, Col, Popconfirm, Select,message} from 'antd';
import {connect} from 'umi';
import moment from 'moment';
import {SearchOutlined} from '@ant-design/icons';
import SelectUserModal from "@/pages/components/SelectUserModal";

const FormItem = Form.Item;
const {Option} = Select;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const AddForm = (props) => {
  const {onSubmit, onCancel, loading, visible, currentUser = {}, contractList,contractData} = props;
  const [form] = Form.useForm();
  const [beforeInfo, setBeforeInfo] = useState(null);
  const [userModalVisible, setUserModalVisible] = useState(false);

  useEffect(() => {
    if (currentUser && visible) {
      form.setFieldsValue({
        applyName: currentUser.name,
        applyCode: currentUser.usercode,
        applyTime: moment(),
        applyPhone: currentUser.mobile
      });
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    setBeforeInfo(null);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...fieldsValue,status:1, oid: beforeInfo.oid});
    setBeforeInfo(null);
  };

  const showSelectUserModal = () => {
    setUserModalVisible(true);
  };

  const confirmSelectUser = (info) => {
    if (info.length > 0) {
      if(info[0].employeestatus === '3'){
        setBeforeInfo(info[0]);
        form.setFieldsValue({
          ...info[0],
          name: info[0].name,
          orgname: info[0].orgname,
          unitname: info[0].unitname,
          jobname: info[0].jobname,
          dimissionTime:info[0].dimissionTime && moment(info[0].dimissionTime)
        });
      }else{
        message.error('该员工目前在职，请通知员工本人发起!');
      }
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="已离职人员" rules={[{required: true, message: '已离职人员不能为空'}]}>
              <Input.Group compact size="large">
                <Input style={{width: '80%',background: '#ffffff', height: '32px', fontSize: '14px'}} placeholder="选择已离职人员"
                       value={beforeInfo ? beforeInfo.name:''} disabled={true}/>
                <Button style={{width: '20%'}} icon={<SearchOutlined/>} onClick={() => showSelectUserModal()}/>
              </Input.Group>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgname" label="所属公司">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="所属部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="任职岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="dimissionTime" label="离职日期" rules={[{required: true, message: '离职日期不能为空'}]}>
              <DatePicker className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyCode" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请日期">
              <DatePicker className='widthStyle' disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyPhone" label="申请人联系电话">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="companyId" label="甲方主体" rules={[{required: true, message: '甲方主体不能为空'}]}>
              <Select placeholder="请选择甲方主体" showSearch
                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      allowClear>
                {contractData && contractData.map((item, index) => {
                  return (
                    <Option value={item.id} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="modelId" label="证明模板" rules={[{required: true, message: '证明模板不能为空'}]}>
              <Select placeholder="请选择证明模板">
                {contractList.map((item, index) => {
                  return (
                    <Option value={item.id} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Popconfirm title={`是否发起证明申请?`}
                    onConfirm={() => handleSubmit()}
                    okText="是" cancelText="否">
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      title='证明申请（已离职人员）'
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消">
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}>
        {renderContent()}
      </Form>
      <SelectUserModal
        isDismiss={true}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />
    </Modal>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser
}))(AddForm)
